<template>
  <div>
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>好稿自荐-每月1号自动开启-每人选两篇</span>
        </div>
      </template>
      <el-table
        :data="tableData"
        style="width: 100%; margin-top: 20px"
        :row-class-name="tableRowClassName"
        :row-click-expand="true"
        class="my-table"
      >
        <el-table-column type="expand">
          <template #default="scope">
            <div v-if="Array.isArray(scope.row.urls)" style="margin-left: 50px">
              <template v-for="(url, index) in scope.row.urls">
                <img
                  v-if="isImage(url)"
                  :src="`${baseURL}/${url}`"
                  alt="image"
                  style="width: 125px; margin-right: 10px"
                />
                <video
                  v-else
                  :src="`${baseURL}/${url}`"
                  controls
                  style="width: 125px; margin-right: 10px"
                ></video>
              </template>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="product_name" label="项目名称" />
        <el-table-column prop="member" label="参与人员">
          <template #default="scope">
            <el-tag
              class="ml-2"
              v-for="name in scope.row.member.split(',')"
              :key="name"
              @click="nameClick(name)"
              >{{ name }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column prop="department_name" label="部门" />
        <el-table-column prop="work_date" label="提交时间">
          <template #default="scope">
            {{
              new Date(
                new Date(scope.row.work_date).getTime() + 8 * 60 * 60 * 1000
              )
                .toISOString()
                .split('T')[0]
            }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160">
          <template #default="scope">
            <el-button type="danger" v-if="ids.includes(scope.row.id)"
              @click="recommendPaper(scope.row.id, scope.row.product_name)" disabled
              >已推荐</el-button
            >
            <el-button v-else
              @click="recommendPaper(scope.row.id, scope.row.product_name)"  :disabled="ids.length === 2"
              >自荐为好稿</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import paperApi from '../../api/paper'
const tableData = ref([])
const recommendData = ref([])
const ids = ref([]) //自荐的id数组
// 获取全局变量
const baseURL = window.globalConfig.baseURL

onMounted(async () => {
   getList()
})

const getList = async () =>{
  const username = sessionStorage.getItem('username')
  await getLastMonthPaperByUser(username)
  await getRecommendPaperByUser(username)

  // 清空ids数组
  ids.value = [];

  //作比较 看能否继续自荐
  tableData.value.forEach((itemA) => {
    recommendData.value.forEach((itemB) => {
      // 检查是否存在匹配
      if (itemA.id === itemB.order_id) {
        // 记录匹配的 ID
        ids.value.push(itemA.id)
      }
    })
  })
}

// 获取数据列表
const getLastMonthPaperByUser = async (username) => {
  const data = {
    username: username,
  }
  const res = await paperApi.getLastMonthPaperByUser(data)
  const resData = res.data
  // 创建一个 Map 对象，用于存储相同 id 的数据
  const idMap = new Map()

  // 遍历数据数组，将具有相同 id 的数据的 url 合并到一个数组中
  resData.forEach((item) => {
    const id = item.id
    if (idMap.has(id)) {
      idMap.get(id).urls.push(item.url)
    } else {
      idMap.set(id, { ...item, urls: [item.url] })
    }
  })

  // 将 Map 对象转换为数组
  const result = Array.from(idMap.values())
  tableData.value = result
}

//获取到自荐过的好稿
const getRecommendPaperByUser = async (username) => {
  const data = {
    username: username,
  }
  const res = await paperApi.getRecommendPaperByUser(data)
  recommendData.value = res.data
}

function isImage(url) {
  const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp']
  const ext = url.substring(url.lastIndexOf('.')).toLowerCase()
  return imageExtensions.includes(ext)
}

const recommendPaper = (id, name) => {
  ElMessageBox.confirm(`确定要推荐${name}吗?（选择后不可更改）`, {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const username = sessionStorage.getItem('username')
      const type = sessionStorage.getItem('type')
      const data = {
        id: id,
        recommender: username,
        type: type,
      }
      const res = await paperApi.recommendPaper(data)
      console.log(res.data)
      if (res.data.id) {
        ElMessage.success('自荐成功')
        //修改按钮样式
        getList()
      } else {
        ElMessage.error('自荐失败')
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消自荐',
      })
    })
}
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.box-card {
  width: 100%;
  height: 100%;
}
.el-tag {
  margin: 5px 5px 5px 0;
}
</style>
